<?php

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class Admin extends Model
{
    //软删除
    use SoftDelete;

    //只读字段
    protected $readonly = ['username', 'eamil'];

    //登陆校验
    public function login($data)
    {
        $validate = new \app\common\validate\Admin();
        if (!$validate->scene('login')->check($data)) {
            return $validate->getError();
        }
        $result = $this->where($data)->find();
        //判断是否存在
        if ($result) {
            //判断是否禁用
            if ($result['status'] != 1) {
                return '此用户被禁用';
            }
            session('admin', [
                'id' => $result['id'],
                'nickname' => $result['nickname'],
                'is_super' => $result['is_super']
            ]);
            return 1;
        } else {
            return '用户名或者密码错误';
        }
    }

    //注册账户
    public function register($data)
    {
        $validate = new \app\common\validate\Admin();
        if (!$validate->scene('register')->check($data)) {
            return $validate->getError();
        }
        $result = $this->allowField(true)->save($data);
        if ($result) {
            mail($data['email'],'个人博客注册成功','恭喜你，管理员注册成功！');
            return 1;
        } else {
            return '注册失败';
        }
    }

    //忘记密码
    public function forget($data){
        $result = $this->whereIn('email', $data['email'])->find();
        if ($result){
            return 1;
        }else{
            return '邮箱未注册';
        }

    }

    //状态改变
    public function status($data){
        $adminInfo = $this->find($data['id']);
        $adminInfo->status = $data['status'] ? 0 : 1;
        $result = $adminInfo->save();
        if ($result){
            return 1;
        }else{
            return '操作失败';
        }
    }

    //添加
    public function add($data){
        $validate = new \app\common\validate\Admin();
        if (!$validate->scene('add')->check($data)){
            return $validate->getError();
        }
        $result = $this->allowField(true)->save($data);
        if ($result){
            return 1;
        }else{
            return '添加失败';
        }
    }

    //修改
    public function edit($data){
        $validate = new \app\common\validate\Admin();
        if (!$validate->scene('edit')->check($data)){
            return $validate->getError();
        }
        $adminInfo = $this->find($data['id']);
        if ($data['oldpass'] != $adminInfo['password']){
            return '原密码错误';
        }
        $adminInfo->nickname = $data['nickname'];
        $adminInfo->password = $data['password'];
        $result = $adminInfo->save();
        if ($result){
            return 1;
        }else{
            return '编辑失败';
        }
    }
}
